#include "rabbitmq.h"
#include "date.h"
namespace Rabbitmq
{
	Rabbitmq::Rabbitmq(const std::string& connect_string,
		const std::string& exchange,
		const std::string& queue_name) :m_connect_string(connect_string),
		m_exchange(exchange),
		m_queue_name(queue_name)
	{

	}

	Rabbitmq::~Rabbitmq()
	{
		if (nullptr != p_amqp)
		{
			delete p_amqp;
			p_amqp = nullptr;
		}
	}

	bool Rabbitmq::sendData(uint8_t* data, size_t len)
	{
		try {
			// 如果
			if (nullptr == p_amqp)
			{
				p_amqp = new AMQP(m_connect_string);
				p_exchange = p_amqp->createExchange(m_exchange);
				p_exchange->Declare(m_exchange, "fanout");

				std::string queue_name = m_queue_name + " connect time:["+Date::Date::getNowTime()+"]";
				AMQPQueue* qu2 = p_amqp->createQueue(queue_name);
				//qu2->Consume(AMQP_EXCLUSIVE);
				qu2->Declare(queue_name, AMQP_EXCLUSIVE);
				qu2->Bind(m_exchange, "");
				



				p_exchange->setHeader("Delivery-mode", 2);
				p_exchange->setHeader("Content-type", "text/text");
				p_exchange->setHeader("Content-encoding", "UTF-8");
			}

			if (data == nullptr)
			{
				return false;
			}

			if (p_exchange != nullptr)
			{
				p_exchange->Publish((char*)data, (uint32_t)len,"");
			}
			
		}
		catch (AMQPException e) {
			if (nullptr != p_amqp)
			{
				delete p_amqp;
				p_amqp = nullptr;
				p_exchange = nullptr;
			}
			std::cout << e.getMessage() << std::endl;
			return false;
		}
		return true;
	}
}
